package com.web709.config;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class FastJsonConfig {

    @Bean
    public HttpMessageConverter<Object> fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        com.alibaba.fastjson.support.config.FastJsonConfig config = new com.alibaba.fastjson.support.config.FastJsonConfig();
        config.setSerializerFeatures(
            SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteNullStringAsEmpty
        );

        // 创建独立序列化配置
        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.put(LocalDateTime.class, new LocalDateTimeSerializer());
        config.setSerializeConfig(serializeConfig);

        converter.setFastJsonConfig(config);
        return converter;
    }

    private static class LocalDateTimeSerializer implements ObjectSerializer {
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        @Override
        public void write(JSONSerializer serializer, Object object,
                          Object fieldName, Type fieldType, int features) throws IOException {
            if (object instanceof LocalDateTime) {
                String formatted = ((LocalDateTime) object).format(FORMATTER);
                serializer.write(formatted);
            }
        }
    }
}
